<!--
 * @Descripttion: (用户表/sys_user)
 * @Author: (admin)
 * @Date: (2025-08-06)
-->
<template>
  <div>
    <el-form :model="queryParams" label-position="right" inline ref="queryRef" v-show="showSearch" @submit.prevent>
      <el-form-item>
        <el-button icon="search" type="primary" @click="handleQuery">{{ $t('btn.search') }}</el-button>
        <el-button icon="refresh" @click="resetQuery">{{ $t('btn.reset') }}</el-button>
      </el-form-item>
    </el-form>
    <!-- 工具区域 -->
    <el-row :gutter="15" class="mb10">
      <el-col :span="1.5">
        <el-button type="primary" v-hasPermi="['user:add']" plain icon="plus" @click="handleAdd">
          {{ $t('btn.add') }}
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <el-table
      :data="dataList"
      v-loading="loading"
      ref="table"
      border
      header-cell-class-name="el-table-header-cell"
      highlight-current-row
      @sort-change="sortChange"
      >
      <el-table-column prop="delFlag" label="删除标志（0代表存在 2代表删除）" align="center" v-if="columns.showColumn('delFlag')"/>
      <el-table-column prop="remark" label="Remark" align="center" :show-overflow-tooltip="true" v-if="columns.showColumn('remark')"/>
      <el-table-column prop="updateTime" label="更新时间" :show-overflow-tooltip="true"  v-if="columns.showColumn('updateTime')"/>
      <el-table-column prop="updateBy" label="更新人" align="center" :show-overflow-tooltip="true" v-if="columns.showColumn('updateBy')"/>
      <el-table-column prop="createTime" label="创建时间" :show-overflow-tooltip="true"  v-if="columns.showColumn('createTime')"/>
      <el-table-column prop="createBy" label="创建人" align="center" :show-overflow-tooltip="true" v-if="columns.showColumn('createBy')"/>
      <el-table-column prop="city" label="City" align="center" :show-overflow-tooltip="true" v-if="columns.showColumn('city')"/>
      <el-table-column prop="province" label="Province" align="center" :show-overflow-tooltip="true" v-if="columns.showColumn('province')"/>
      <el-table-column prop="deptId" label="部门Id" align="center" v-if="columns.showColumn('deptId')"/>
      <el-table-column prop="loginDate" label="最后登录时间" :show-overflow-tooltip="true"  v-if="columns.showColumn('loginDate')"/>
      <el-table-column prop="loginIP" label="最后登录IP" align="center" :show-overflow-tooltip="true" v-if="columns.showColumn('loginIP')"/>
      <el-table-column prop="userId" label="用户id" align="center" v-if="columns.showColumn('userId')"/>
      <el-table-column prop="status" label="帐号状态（0正常 1停用）" align="center" v-if="columns.showColumn('status')">
        <template #default="scope">
          <dict-tag :options=" options.statusOptions" :value="scope.row.status"  />
        </template>
      </el-table-column>
      <el-table-column prop="sex" label="用户性别（0男 1女 2未知）" align="center" v-if="columns.showColumn('sex')">
        <template #default="scope">
          <dict-tag :options=" options.sexOptions" :value="scope.row.sex"  />
        </template>
      </el-table-column>
      <el-table-column prop="phonenumber" label="手机号" align="center" :show-overflow-tooltip="true" v-if="columns.showColumn('phonenumber')"/>
      <el-table-column prop="password" label="密码" align="center" :show-overflow-tooltip="true" v-if="columns.showColumn('password')"/>
      <el-table-column prop="email" label="用户邮箱" align="center" :show-overflow-tooltip="true" v-if="columns.showColumn('email')"/>
      <el-table-column prop="avatar" label="Avatar" align="center" v-if="columns.showColumn('avatar')">
        <template #default="scope">
          <ImagePreview :src="scope.row.avatar"></ImagePreview>
        </template>
      </el-table-column>
      <el-table-column prop="userType" label="用户类型（00系统用户）" align="center" v-if="columns.showColumn('userType')">
        <template #default="scope">
          <dict-tag :options=" options.userTypeOptions" :value="scope.row.userType"  />
        </template>
      </el-table-column>
      <el-table-column prop="nickName" label="用户昵称" align="center" :show-overflow-tooltip="true" v-if="columns.showColumn('nickName')"/>
      <el-table-column prop="userName" label="用户账号" align="center" :show-overflow-tooltip="true" v-if="columns.showColumn('userName')"/>
      <el-table-column label="操作" width="160">
        <template #default="scope">
          <el-button type="success" size="small" icon="edit" title="编辑" v-hasPermi="['user:edit']" @click="handleUpdate(scope.row)"></el-button>
          <el-button type="danger" size="small" icon="delete" title="删除" v-hasPermi="['user:delete']" @click="handleDelete(scope.row)"></el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />


    <el-dialog :title="title" :lock-scroll="false" v-model="open" >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
            
          <el-col :lg="12">
            <el-form-item label="删除标志（0代表存在 2代表删除）" prop="delFlag">
              <el-input v-model.number="form.delFlag" placeholder="请输入删除标志（0代表存在 2代表删除）" />
            </el-form-item>
          </el-col>

          <el-col :lg="12">
            <el-form-item label="Remark" prop="remark">
              <el-input v-model="form.remark" placeholder="请输入Remark" />
            </el-form-item>
          </el-col>

          <el-col :lg="12">
            <el-form-item label="更新时间" prop="updateTime">
              <el-date-picker
                v-model="form.updateTime"
                type="datetime"
                placeholder="选择日期时间"
                value-format="YYYY-MM-DD HH:mm:ss">
              </el-date-picker>
            </el-form-item>
          </el-col>

          <el-col :lg="12">
            <el-form-item label="更新人" prop="updateBy">
              <el-input v-model="form.updateBy" placeholder="请输入更新人" />
            </el-form-item>
          </el-col>

          <el-col :lg="12">
            <el-form-item label="创建时间" prop="createTime">
              <el-date-picker
                v-model="form.createTime"
                type="datetime"
                placeholder="选择日期时间"
                value-format="YYYY-MM-DD HH:mm:ss">
              </el-date-picker>
            </el-form-item>
          </el-col>

          <el-col :lg="12">
            <el-form-item label="创建人" prop="createBy">
              <el-input v-model="form.createBy" placeholder="请输入创建人" />
            </el-form-item>
          </el-col>

          <el-col :lg="12">
            <el-form-item label="City" prop="city">
              <el-input v-model="form.city" placeholder="请输入City" />
            </el-form-item>
          </el-col>

          <el-col :lg="12">
            <el-form-item label="Province" prop="province">
              <el-input v-model="form.province" placeholder="请输入Province" />
            </el-form-item>
          </el-col>
            
          <el-col :lg="12">
            <el-form-item label="部门Id" prop="deptId">
              <el-input v-model.number="form.deptId" placeholder="请输入部门Id" />
            </el-form-item>
          </el-col>

          <el-col :lg="12">
            <el-form-item label="最后登录时间" prop="loginDate">
              <el-date-picker
                v-model="form.loginDate"
                type="datetime"
                placeholder="选择日期时间"
                value-format="YYYY-MM-DD HH:mm:ss">
              </el-date-picker>
            </el-form-item>
          </el-col>

          <el-col :lg="12">
            <el-form-item label="最后登录IP" prop="loginIP">
              <el-input v-model="form.loginIP" placeholder="请输入最后登录IP" />
            </el-form-item>
          </el-col>
            
            
          <el-col :lg="12">
            <el-form-item label="帐号状态（0正常 1停用）" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio v-for="item in options.statusOptions" :key="item.dictValue" :value="parseInt(item.dictValue)">
                  {{item.dictLabel}}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
            
          <el-col :lg="12">
            <el-form-item label="用户性别（0男 1女 2未知）" prop="sex">
              <el-select v-model="form.sex"  placeholder="请选择用户性别（0男 1女 2未知）">
                <el-option
                  v-for="item in options.sexOptions" 
                  :key="item.dictValue" 
                  :label="item.dictLabel" 
                  :value="parseInt(item.dictValue)"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :lg="12">
            <el-form-item label="手机号" prop="phonenumber">
              <el-input v-model="form.phonenumber" placeholder="请输入手机号" />
            </el-form-item>
          </el-col>

          <el-col :lg="12">
            <el-form-item label="密码" prop="password">
              <el-input v-model="form.password" placeholder="请输入密码" />
            </el-form-item>
          </el-col>

          <el-col :lg="12">
            <el-form-item label="用户邮箱" prop="email">
              <el-input v-model="form.email" placeholder="请输入用户邮箱" />
            </el-form-item>
          </el-col>

          <el-col :lg="24">
            <el-form-item label="Avatar" prop="avatar">
              <UploadImage v-model="form.avatar" :data="{ uploadType: 1 }" />
            </el-form-item>
          </el-col>

          <el-col :lg="12">
            <el-form-item label="用户类型（00系统用户）" prop="userType">
              <el-select v-model="form.userType"  placeholder="请选择用户类型（00系统用户）">
                <el-option
                  v-for="item in options.userTypeOptions" 
                  :key="item.dictValue" 
                  :label="item.dictLabel" 
                  :value="item.dictValue"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :lg="12">
            <el-form-item label="用户昵称" prop="nickName">
              <el-input v-model="form.nickName" placeholder="请输入用户昵称" />
            </el-form-item>
          </el-col>

          <el-col :lg="12">
            <el-form-item label="用户账号" prop="userName">
              <el-input v-model="form.userName" placeholder="请输入用户账号" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer v-if="opertype != 3">
        <el-button text @click="cancel">{{ $t('btn.cancel') }}</el-button>
        <el-button type="primary" :loading="state.submitLoading" @click="submitForm">{{ $t('btn.submit') }}</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="user">
import { listUser,
 addUser, delUser, 
 updateUser,getUser, 
 } 
from '@/api/business/user.js'
const { proxy } = getCurrentInstance()
const ids = ref([])
const loading = ref(false)
const showSearch = ref(true)
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  sort: '',
  sortType: 'asc',
})
const columns = ref([
  { visible: true, align: 'center', type: '', prop: 'delFlag', label: '删除标志（0代表存在 2代表删除）'   },
  { visible: true, align: 'center', type: '', prop: 'remark', label: 'Remark'  ,showOverflowTooltip: true  },
  { visible: true, align: 'center', type: '', prop: 'updateTime', label: '更新时间'  ,showOverflowTooltip: true  },
  { visible: true, align: 'center', type: '', prop: 'updateBy', label: '更新人'  ,showOverflowTooltip: true  },
  { visible: true, align: 'center', type: '', prop: 'createTime', label: '创建时间'  ,showOverflowTooltip: true  },
  { visible: true, align: 'center', type: '', prop: 'createBy', label: '创建人'  ,showOverflowTooltip: true  },
  { visible: true, align: 'center', type: '', prop: 'city', label: 'City'  ,showOverflowTooltip: true  },
  { visible: true, align: 'center', type: '', prop: 'province', label: 'Province'  ,showOverflowTooltip: true  },
  { visible: false, align: 'center', type: '', prop: 'deptId', label: '部门Id'   },
  { visible: false, align: 'center', type: '', prop: 'loginDate', label: '最后登录时间'  ,showOverflowTooltip: true  },
  { visible: false, align: 'center', type: '', prop: 'loginIP', label: '最后登录IP'  ,showOverflowTooltip: true  },
  { visible: false, align: 'center', type: '', prop: 'userId', label: '用户id'   },
  { visible: false, align: 'center', type: 'dict', prop: 'status', label: '帐号状态（0正常 1停用）'   },
  { visible: false, align: 'center', type: 'dict', prop: 'sex', label: '用户性别（0男 1女 2未知）'   },
  { visible: false, align: 'center', type: '', prop: 'phonenumber', label: '手机号'  ,showOverflowTooltip: true  },
  { visible: false, align: 'center', type: '', prop: 'password', label: '密码'  ,showOverflowTooltip: true  },
  { visible: false, align: 'center', type: '', prop: 'email', label: '用户邮箱'  ,showOverflowTooltip: true  },
  { visible: false, align: 'center', type: 'img', prop: 'avatar', label: 'Avatar'  ,showOverflowTooltip: true  },
  { visible: false, align: 'center', type: 'dict', prop: 'userType', label: '用户类型（00系统用户）'  ,showOverflowTooltip: true  },
  { visible: false, align: 'center', type: '', prop: 'nickName', label: '用户昵称'  ,showOverflowTooltip: true  },
  { visible: false, align: 'center', type: '', prop: 'userName', label: '用户账号'  ,showOverflowTooltip: true  },
  //{ visible: false, prop: 'actions', label: '操作', type: 'slot', width: '160' }
])
const total = ref(0)
const dataList = ref([])
const queryRef = ref()
const defaultTime = ref([new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 2, 1, 23, 59, 59)])


var dictParams = [
]


function getList(){
  loading.value = true
  listUser(queryParams).then(res => {
    const { code, data } = res
    if (code == 200) {
      dataList.value = data.result
      total.value = data.totalNum
      loading.value = false
    }
  })
}

// 查询
function handleQuery() {
  queryParams.pageNum = 1
  getList()
}

// 重置查询操作
function resetQuery(){
  proxy.resetForm("queryRef")
  handleQuery()
}
// 自定义排序
function sortChange(column) {
  var sort = undefined
  var sortType = undefined

  if (column.prop != null && column.order != null) {
    sort = column.prop
    sortType = column.order

  }
  queryParams.sort = sort
  queryParams.sortType = sortType
  handleQuery()
}

/*************** form操作 ***************/
const formRef = ref()
const title = ref('')
// 操作类型 1、add 2、edit 3、view
const opertype = ref(0)
const open = ref(false)
const state = reactive({
  single: true,
  multiple: true,
  submitLoading: false,
  form: {},
  rules: {
    password: [{ required: true, message: "密码不能为空", trigger: "blur"     }],
    nickName: [{ required: true, message: "用户昵称不能为空", trigger: "blur"     }],
    userName: [{ required: true, message: "用户账号不能为空", trigger: "blur"     }],
  },
  options: {
    // 帐号状态（0正常 1停用） 选项列表 格式 eg:{ dictLabel: '标签', dictValue: '0'}
statusOptions: [],
  }
})

const { form, rules, options, single, multiple } = toRefs(state)

// 关闭dialog
function cancel(){
  open.value = false
  reset()
}

// 重置表单
function reset() {
  form.value = {
    delFlag: null,
    remark: null,
    updateTime: null,
    updateBy: null,
    createTime: null,
    createBy: null,
    city: null,
    province: null,
    deptId: null,
    loginDate: null,
    loginIP: null,
    userId: null,
    status: null,
    sex: null,
    phonenumber: null,
    password: null,
    email: null,
    avatar: null,
    userType: null,
    nickName: null,
    userName: null,
  };
  proxy.resetForm("formRef")
}


// 添加按钮操作
function handleAdd() {
  reset();
  open.value = true
  state.submitLoading = false
  title.value = '添加用户表'
  opertype.value = 1
}
// 修改按钮操作
function handleUpdate(row) {
  reset()
  const id = row.userId || ids.value
  getUser(id).then((res) => {
    const { code, data } = res
    if (code == 200) {
      open.value = true
      title.value = '修改用户表'
      opertype.value = 2

      form.value = {
        ...data,
      }
    }
  })
}

// 添加&修改 表单提交
function submitForm() {
  proxy.$refs["formRef"].validate((valid) => {
    if (valid) {
      state.submitLoading = true

      if (form.value.userId != undefined && opertype.value === 2) {
        updateUser(form.value).then((res) => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
        .finally(() => {
          state.submitLoading = false
        })
      } else {
        addUser(form.value).then((res) => {
            proxy.$modal.msgSuccess("新增成功")
            open.value = false
            getList()
          })
          .finally(() => {
            setTimeout(() => {
              state.submitLoading = false
            }, 800)
          })
      }
    }
  })
}

// 删除按钮操作
function handleDelete(row) {
  const Ids = row.userId || ids.value

  proxy
    .$confirm('是否确认删除参数编号为"' + Ids + '"的数据项？', "警告", {
      confirmButtonText: proxy.$t('common.ok'),
      cancelButtonText: proxy.$t('common.cancel'),
      type: "warning",
    })
    .then(function () {
      return delUser(Ids)
    })
    .then(() => {
      getList()
      proxy.$modal.msgSuccess("删除成功")
    })
}




handleQuery()
</script>